﻿using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.Analysis.TableRef
{
    public class OnePartObjectIdentifierAnalysis : SqlAnalysisBase
    {
        public OnePartObjectIdentifierAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            var tableRef = (SqlObjectIdentifier)base.CodeObject;

            string tableName = tableRef.ObjectName.Value;
            if (string.IsNullOrWhiteSpace(tableRef.ObjectName.Value))
            {
                tableName = tableRef.ObjectName.Sql;
            }


            switch (base.context)
            {
                case var t when t is SqlSelectAnalysisContext:
                    ((SqlSelectAnalysisContext)base.context).QueryTables.Add(new SQLTableOptions
                    {
                        Name = tableName
                    });
                    break;
                case var t when t is SqlUpdateAnalysisContext || t is SqlDeleteAnalysisContext || t is SqlInsertAnalysisContext:
                    base.context.Table = new SQLTableOptions
                    {
                        Name = tableName
                    };
                    break;
            }
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
